% This script constructs a linear system of equations to be used to
% solve for structural parameters from reduced-form coefficients.
% Date: 2018-11-25
function [Mat,Vec] = constructLS(a,b,M)
% INPUT
% -- a,b : (K-1)-by-L array of constants solved from RRC, where
%           K = # of individual characteristics 
%           L = # of class size groups
% -- M   :  K-by-L array of (beta_k+gamma_k)/(1-lambda)
% OUTPUT
% -- Mat : coefficient matrix for solving structural parameters
% -- Vec : vector of constants
% The dimension of output arrays depend on the type of exclusion
% restrictions used
K = size(a,1)+1; L = size(a,2);
%% construct linear system using (a,b) alone
Phi = zeros( L*(2*(K-1)+K) , L+2*K ); 
Mat1 = []; Mat2 = []; CV = [];
for li =  1:L,
            % fill one of the first L columns in Phi
            vec = zeros(L,1); vec(li) = 1; 
            vci = zeros( 2*(K-1)+K,1 ); 
            vci( 2*(K-1)+1:end ) = M(:,li); 
            vci(K:2*(K-1)) = ones(K-1,1);
            Phi(:,li) = kron(vec,vci);
            % construct component matrices for the other 2K columns
            mat1 = zeros(2*(K-1)+K,K); 
            mat1(1:K-1,:) = [diag(a(:,li)) b(:,li)];
            mat1( 2*(K-1)+1:end ,:) = eye(K);  
            Mat1 = [Mat1;mat1];     
            mat2 = zeros(2*(K-1)+K,K); 
            mat2(K:2*(K-1),:) = [diag(a(:,li)) b(:,li)];    
            mat2( 2*(K-1)+1:end ,:) = eye(K);    
            Mat2 = [Mat2;-mat2];    
            cvec = [ones(K-1,1); zeros(K-1,1); M(:,li)];
            CV   = [CV; cvec];
end;
Phi(:,L+1:end) = [Mat1,Mat2];   
% impose 'days of absence' has no contextual effect
Mat = [Phi; zeros(1,L+2*K)]; Mat(end,L+K+1) = 1;
Vec = [CV; 0];        
